package itstudio.instructor.fragment;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import itstudio.app.wq.R;
import itstudio.instructor.adapter.NewsListAdapterNoHead;
import itstudio.instructor.config.Config;
import itstudio.instructor.config.ImageOptionsUtil;
import itstudio.instructor.config.MyApplication;
import itstudio.instructor.entity.News;
import itstudio.instructor.entity.User;
import itstudio.instructor.http.TwitterRestClient;
import itstudio.instructor.ui.ReviseInfoActivity;
import itstudio.instructor.ui.MyFansActivity;
import itstudio.instructor.ui.MyFollowActivity;
import itstudio.instructor.ui.NewsDetailActivity;
import itstudio.instructor.widget.PullScrollView;
import itstudio.instructor.xlistview.XListView;
import itstudio.instructor.xlistview.XListView.IXListViewListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class FragmentSelf extends Fragment implements IXListViewListener, PullScrollView.OnTurnListener{

	public static FragmentActivity mactivity;
	
	//config
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	protected DisplayImageOptions options;
	//view
    private LinearLayout loadingLayout;
    private View loadNoneLayout;
    private View v_line;
    private View post_layout;
    private LinearLayout bt_revise_user_info;
    private LinearLayout layout_follow;
    private LinearLayout layout_fans;
	TextView name_tv ;
	TextView fansnum_tv ;
	TextView follownum_tv ;
	TextView newsnum_tv ;
	TextView intro_tv ;
	ImageView headImg ;
    
	private XListView xListView;
	private PullScrollView mScrollView;
	private ImageView mHeadImg;
	private View rootView;
	//data
	private int page=0;
	private User user = MyApplication.user;
	private NewsListAdapterNoHead adapter;
	private List<News> newsList = new ArrayList<News>();;
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mactivity = getActivity();
		options = ImageOptionsUtil.headImageOptions();
		rootView = inflater.inflate(R.layout.frament_user_info, container,false);
		findViewById();
		setOnclick();
		initView();
		return rootView;

	}
	
	protected void findViewById() {
		
		bt_revise_user_info = (LinearLayout) rootView.findViewById(R.id.revise_user_info_layout);
		layout_follow = (LinearLayout) rootView.findViewById(R.id.user_info_follow_layout);
		layout_fans = (LinearLayout) rootView.findViewById(R.id.user_info_fans_layout);
		loadingLayout = (LinearLayout) rootView.findViewById(R.id.view_loading);
		loadNoneLayout = rootView.findViewById(R.id.view_load_nodata);
		name_tv = (TextView) rootView.findViewById(R.id.name_tv);
		fansnum_tv = (TextView) rootView.findViewById(R.id.fans_num);
		follownum_tv = (TextView) rootView.findViewById(R.id.follow_num);
		newsnum_tv = (TextView) rootView.findViewById(R.id.news_num);
		intro_tv = (TextView) rootView.findViewById(R.id.intro_tv);
		v_line = rootView.findViewById(R.id.v_line);
		post_layout = rootView.findViewById(R.id.user_info_post_layout);
		if(MyApplication.user.getStatus()==User.STATUS_STUDENT){
			v_line.setVisibility(View.GONE);
			post_layout.setVisibility(View.GONE);
		}
		headImg = (ImageView) rootView.findViewById(R.id.headImg);
		
		User user = MyApplication.user;
		name_tv.setText(user.getName());
		fansnum_tv.setText(user.getFansNum().toString());
		follownum_tv.setText(user.getFollowNum().toString());
		newsnum_tv.setText(user.getNewsNum().toString());
		intro_tv.setText(user.getIntro());
		imageLoader.displayImage(Config.HEAD_URL +user.getHeadUrl(),
				headImg, options);
	}

	protected void setOnclick() {
		MyOnClick onclick = new MyOnClick();
		bt_revise_user_info.setOnClickListener(onclick);
		layout_follow.setOnClickListener(onclick);
		layout_fans.setOnClickListener(onclick);

	}

	class MyOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			switch (v.getId()) {

			case R.id.revise_user_info_layout:
				intent.setClass(mactivity,
						ReviseInfoActivity.class);
				startActivity(intent);
				break;
			case R.id.user_info_follow_layout:
				intent.setClass(mactivity, MyFollowActivity.class);
				startActivity(intent);
				break;
			case R.id.user_info_fans_layout:
				intent.setClass(mactivity, MyFansActivity.class);
				startActivity(intent);
				break;

			default:
				break;
			}

		}

	}

	// 填充listview
	protected void initView() {
		mScrollView = (PullScrollView) rootView.findViewById(R.id.user_info_scroll_view_test);
		mHeadImg = (ImageView) rootView.findViewById(R.id.background_img_user_info_test);
		mScrollView.smoothScrollTo(0, 20);
		mScrollView.setHeader(mHeadImg);
		mScrollView.setOnTurnListener(this);
		xListView = (XListView) rootView.findViewById(R.id.listviewTest);
		xListView.setPullLoadEnable(true);
		xListView.setPullRefreshEnable(false);// 取消下拉刷新
		adapter = new NewsListAdapterNoHead(mactivity, newsList,R.layout.listitem_news_no_head);
		xListView.setAdapter(adapter);
		xListView.setXListViewListener(FragmentSelf.this);	
		xListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				TextView list_item_title=(TextView) arg1.findViewById(R.id.list_item_title);
				list_item_title.setTextColor(getResources().getColor(R.color.light_black));

				Intent intent = new Intent();
				intent.setClass(mactivity, NewsDetailActivity.class);
				News news = (News) adapter.getItem(position-1); 
				news.setUser(user);//必须手动设置
				intent.putExtra("news", news);
				startActivity(intent);
				
			}
		});

		setListViewHeightBasedOnChildren(xListView);
		loadNews();


	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		User user = MyApplication.user;
		name_tv.setText(user.getName());
		fansnum_tv.setText(user.getFansNum().toString());
		follownum_tv.setText(user.getFollowNum().toString());
		newsnum_tv.setText(user.getNewsNum().toString());
		intro_tv.setText(user.getIntro());
		imageLoader.displayImage(Config.HEAD_URL +user.getHeadUrl(),
				headImg, options);
	}
	//加载news 
		private void loadNews(){
			RequestParams params = new RequestParams();
			params.put("page", page+1);
			params.put("user.id", user.getId());
			String url = Config.AC_NEWS_PERSON;
			if(MyApplication.user.getStatus()==User.STATUS_STUDENT){
				url = Config.AC_NEWS_FOLLOW;
			}
			TwitterRestClient.post(url, params, new AsyncHttpResponseHandler(){
				
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					onLoad();
					loadingLayout.setVisibility(View.GONE);
					loadNoneLayout.setVisibility(View.VISIBLE);
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					//加载成功
					loadingLayout.setVisibility(View.GONE);
					onLoad();
					Gson gson = new GsonBuilder()  
					  .setDateFormat("yyyy-MM-dd HH:mm:ss")  
					  .create();
					newsList  = gson.fromJson( new String(arg2), new TypeToken<List<News>>(){}.getType());
					adapter.appendToList(newsList);
					
					if(adapter.getCount()==0){
						loadNoneLayout.setVisibility(View.VISIBLE);
					}
					// 是否有下一页
					if(newsList.size()!=0 && newsList.size()==10){
						xListView.setPullLoadEnable(true);
						page =page+1;
					}
					else{
						xListView.setPullLoadEnable(false);
					}
					setListViewHeightBasedOnChildren(xListView);
					
				}});
		}
	// 解决listview与scrollview冲突问题
	private void setListViewHeightBasedOnChildren(ListView listView) {

		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		loadNews();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		loadNews();

	}

	private void onLoad() {
		xListView.stopRefresh();
		xListView.stopLoadMore();
		xListView.setRefreshTime("刚刚");
	}

	@Override
	public void onTurn() {
		// TODO Auto-generated method stub
	}

	@Override
	public void onScrollChanged(PullScrollView scrollView, int x, int y,
			int oldx, int oldy) {
		// We take the last son in the scrollview
		View view = (View) scrollView
				.getChildAt(scrollView.getChildCount() - 1);
		int diff = (view.getBottom() - (scrollView.getHeight() + scrollView
				.getScrollY()));
		// if diff is zero, then the bottom has been reached
		if (diff == 0) {
			// do stuff
		}
	}


}
